package com.example.attendancesystem.Handler;


import com.example.attendancesystem.Models.*;
import com.example.attendancesystem.Service.IndexService;
import com.example.attendancesystem.Tools.Excel;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private IndexService indexService;


    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 分页查询所有员工信息
     *
     * @param page  页码
     * @param limit 每页限制条数
     * @return DataV0对象
     */
    @RequestMapping("/getAllEmp")
    @ResponseBody
    public DataEmp getAllEmp(Integer page, Integer limit) {
        int offset = (page - 1) * limit;  // 数据库从第几条记录开始
        DataEmp dataEmp;
        dataEmp = indexService.getAllEmp(offset, limit);
        return dataEmp;
    }

    /**
     * 员工信息重新页面
     *
     * @param page  页面
     * @param limit 页面大小
     * @param emp   员工号或者员工姓名
     * @return DataV0类型
     */
    @RequestMapping("/queryEmpByNameOrNumber")
    @ResponseBody
    public DataEmp queryEmpByNameOrNumber(Integer page, Integer limit, String emp) {
        int offset = (page - 1) * limit;  // 数据库从第几条记录开始
        DataEmp dataEmp;
        dataEmp = indexService.queryEmpByNameOrNumber(offset, limit, emp);
        return dataEmp;
    }

    /**
     * 删除员工信息
     *
     * @param operaPass 管理员操作密码
     * @param empNumber 员工工号
     * @return Integer对象 1001 成功， 1002 失败， 1003  管理员密码错误
     */
    @RequestMapping("/delEmpByNumber")
    @ResponseBody
    public Integer delEmpByNumber(String operaPass, String empNumber, HttpSession session) {
        int res;
        try {
            // 判断管理员密码是否正确
            Admin admin = (Admin) session.getAttribute("admin");
            String adminNumber = admin.getAdminNumber();
            if (!indexService.checkOPRTPass(adminNumber, operaPass)) {
                res = 1003;
            } else {
                //管理员密码正确 执行删除操作
                if (indexService.delEmpByNumber(empNumber)) res = 1001;
                else res = 1002;
            }
        } catch (Exception e) {
            res = 1002;
        }
        return res;
    }

    /**
     * 管理员按员工号查询员工信息
     *
     * @return 员工信息对象
     */
    @RequestMapping("/getEmpInfoByNumber")
    @ResponseBody
    public Employee getEmpInfoByNumber(String empNumber) {
        Employee employee;
        employee = indexService.getEmpInfoByNumber(empNumber);
        employee.setEmpPassword("");
        employee.setQues("");
        employee.setAns("");
        return employee;
    }

    /**
     * 查找未处理员工请假请求
     *
     * @return DataV2对象
     */
    @RequestMapping("/getEmpLeaveRequest")
    @ResponseBody
    public DataLeaveRow getEmpLeaveRequest() {
        DataLeaveRow dataLeaveRow;
        dataLeaveRow = indexService.getEmpLeaveRequest();
        return dataLeaveRow;
    }

    /**
     * 查询请假请求数量
     *
     * @return Integer 数量
     */
    @RequestMapping("/getLeaveRequestSum")
    @ResponseBody
    public Integer getLeaveRequestSum() {
        int sum;
        sum = indexService.getLeaveRequestSum();
        return sum;
    }

    /**
     * 处理请假请求
     *
     * @param result    结果
     * @param requestId 请假请求Id
     * @return Boolean对象 true 成功 false 失败
     */
    @RequestMapping("/dealLeaveRequest")
    @ResponseBody
    public Boolean dealLeaveRequest(Integer result, Integer requestId) {
        Boolean flag;
        flag = indexService.dealLeaveRequest(result, requestId);
        return flag;
    }


    /**
     * 添加新员工
     *
     * @param addEmpName       员工姓名
     * @param addEmpTel        电话
     * @param addEmpEmail      邮箱
     * @param addEmpDepartment 所属部门
     * @param addEmpPosition   职位
     * @param addEmpGender     性别
     * @param addEmpEdu        学历
     * @param addEmpBirthday   出生日期
     * @param address          地址
     * @return 添加成功详细信息
     */
    @RequestMapping("/addEmp")
    @ResponseBody
    public Employee addEmp(String addEmpName, String addEmpTel, String addEmpEmail, String addEmpDepartment, String addEmpPosition,
                           String addEmpGender, String addEmpEdu, String addEmpBirthday, String address) {
        Employee addEmp = new Employee();
        Employee res;
        addEmp.setEmpName(addEmpName);
        addEmp.setEmpTel(addEmpTel);
        addEmp.setEmpEmail(addEmpEmail);
        addEmp.setDepartment(addEmpDepartment);
        addEmp.setEmpPosition(addEmpPosition);
        addEmp.setEmpGender(addEmpGender);
        addEmp.setEducation(addEmpEdu);
        addEmp.setBirthday(addEmpBirthday);
        addEmp.setAddress(address);
        addEmp.setImgPath("dafaultEmpImg.jpg"); //头像默认
        res = indexService.addEmp(addEmp);
        return res;
    }


    /**
     * 获取员工密码和密保
     *
     * @param operaPass 管理员操作密码
     * @param empNumber 员工号
     * @param session   session
     * @return 列表
     */
    @RequestMapping("/getEmpPass")
    @ResponseBody
    public List<String> getEmpPass(String operaPass, String empNumber, HttpSession session) {
        List<String> res = new ArrayList<>();
        try {
            // 判断管理员密码是否正确
            Admin admin = (Admin) session.getAttribute("admin");
            String adminNumber = admin.getAdminNumber();
            if (!indexService.checkOPRTPass(adminNumber, operaPass)) {
                res.add("1003");
            } else {
                //管理员密码正确 执行查询操作
                Employee employee = indexService.getEmpInfoByNumber(empNumber);
                res.add("1001");
                res.add(employee.getEmpPassword());
                res.add(employee.getQues());
                res.add(employee.getAns());
            }
        } catch (Exception e) {
            res.add("1002");
        }
        return res;
    }

    /**
     * 更新员工密码、密保、密保答案
     *
     * @param empPass   员工密码
     * @param empQues   密保问题
     * @param empAns    密保答案
     * @param empNumber 要更新的员工号
     * @return boolean对象 true 成功 false 失败
     */
    @RequestMapping("/updateEmpPass")
    @ResponseBody
    public Boolean updateEmpPass(String empPass, String empQues, String empAns, String empNumber) {
        boolean flag;
        flag = indexService.updateEmpPass(empPass, empQues, empAns, empNumber);
        return flag;
    }

    /**
     * 判断管理员密码是否正确
     *
     * @param session session
     * @return Boolean对象 ture 正确 false 错误
     */
    @RequestMapping("/checkPass")
    @ResponseBody
    public Boolean checkPass(HttpSession session, String operaPass) {
        Admin admin = (Admin) session.getAttribute("admin");
        String adminNumber = admin.getAdminNumber();
        return indexService.checkOPRTPass(adminNumber, operaPass);

    }


    /**
     * 下载所有员工的信息导出Excel表格
     *
     * @param response 响应
     * @throws IOException 异常
     */
    @RequestMapping("/downLoadAllEmpFile")
    @ResponseBody
    public void downExcel(HttpServletResponse response) throws IOException {
        String fileName = "全部员工信息.xls";
        //1、查询所有员工信息
        List<Employee> employeeList = indexService.getAllEmpDown();
        //2、将员工信息写入Excel表格中
        Excel.creatStudentExcel(employeeList, fileName);
    }

    /**
     * 修改员工信息
     *
     * @param empNumber           员工号
     * @param updateEmpDepartment 部门
     * @param updateEmpPosition   职务
     * @param updateEmpTel        电话
     * @param updateEmpEmail      邮箱
     * @param updateEmpEdu        学历
     * @return true 成功 false 失败
     */
    @RequestMapping("/updateEmp")
    @ResponseBody
    public Boolean updateEmp(String empNumber, String updateEmpDepartment, String updateEmpPosition, String updateEmpTel, String updateEmpEmail, String updateEmpEdu) {
        boolean flag = false;
        Employee employee = new Employee();
        employee.setEmpNumber(empNumber);
        employee.setDepartment(updateEmpDepartment);
        employee.setEmpPosition(updateEmpPosition);
        employee.setEmpEmail(updateEmpEmail);
        employee.setEmpTel(updateEmpTel);
        employee.setEducation(updateEmpEdu);
        flag = indexService.updateEmpInfo(employee);
        return flag;
    }


    /**
     * 发布一条新闻
     *
     * @param title  标题
     * @param author 作者
     * @param text   内容
     * @return true成功 false 失败
     */
    @RequestMapping("/addNews")
    @ResponseBody
    public Boolean addNews(String title, String author, String text) {
        System.out.println("jinglail");
        return indexService.addNews(title, author, text);
    }

    /**
     * 更新新闻图片
     *
     * @param newsId id
     * @param file   图片文件
     * @return dataV1
     */
    @RequestMapping("/updateNewsImg")
    @ResponseBody
    public DataV1 updateNewsImg(Integer newsId, MultipartFile file) {
        DataV1 dataV1 = new DataV1();
        if (null == newsId || null == file.getOriginalFilename()) {
            dataV1.setCode(0);//上传失败
        } else {
            try {
                String filePath = "F:\\javaproject\\demo5\\src\\main\\resources\\static\\newsImages\\";
                String savaImgName = newsId + ".jpg";
                News news = indexService.getNewsById(newsId);
                if (news.getImgPath().equals("news1.jpg")) {
                    /*保存新的图片*/
                    File saveFile = new File(filePath + savaImgName);
                    OutputStream outputStream = new FileOutputStream(saveFile);
                    IOUtils.copy(file.getInputStream(), outputStream);
                    /*更新数据库信息*/
                } else {
                    //删除原来的图片
                    File oldFile = new File(filePath + news.getImgPath());
                    oldFile.delete();
                    /*保存新的图片*/
                    File saveFile = new File(filePath + savaImgName);
                    OutputStream outputStream = new FileOutputStream(saveFile);
                    IOUtils.copy(file.getInputStream(), outputStream);
                    /*更新数据库信息*/
                }
                /*更新数据库信息*/
                indexService.updateEmpImg(newsId, savaImgName);
                dataV1.setCode(0);//上传成功 修改 数据库的信息
            } catch (Exception e) {
                e.printStackTrace();
                dataV1.setCode(1);//上传失败
            }
        }
        return dataV1;
    }

}
